import React, { useEffect, useState,Key } from 'react'
import { Button, Form, Input, Table, Card, message,Tooltip} from 'antd'
import { SearchOutlined ,EditOutlined,DeleteOutlined} from '@ant-design/icons'
import style from  './index.module.css'
import { getHosSetListRequest, deleteHosSetFromIdRequest,batchDeleteHosRequest} from '@/api/hospital/hospitalSet'
import { getHosSetListRecordsType } from '@/api/hospital/model/hospitalSetTypes' 
import { searchHosFinishPraType } from './type'
import useSelection from 'antd/lib/table/hooks/useSelection'
import { useNavigate } from 'react-router-dom'
import { getHosSetListItemsType } from '@/api/hospital/model/hospitalSetTypes'







export default function HospitalSet() {

  //使用useNavigate
  const  Navigate =useNavigate()
  
  //设置current的初始值
  const [current,setCurrent] = useState(1)
  //设置 records的初始值  注意要使用泛型 
  const [tableData,setTableData] = useState <getHosSetListRecordsType>()
  //设置  total 总数字
  const [total,setTotal] = useState(0)
  //设置 每页条数字
  const [pageSize,setPageSize] = useState(4)
  //定义isLoading 
  const [isLoading, setIsLoading] = useState(false);
  //查询该变
  const [fieldValue,setFieldValue] = useState<searchHosFinishPraType>({})
  //设置一个基本变量 用来删除之后重新渲染
  const [reRender, setReRender] = useState(true)
  //增加一个 初始化配置项  用来普安批量删除功能
  const [isSelecte,setIsSelecte]  = useState(true)

  //定义一个 保存批量删除中的 ids的状态
  const [bacthSelectIds, setBatchSelectIds] =useState<Key[]>([])






    //添加useEffect 因为useEffect内部不能书写异步函数（可能会return一个函数来实现清除作用）加了await后面所有函数都是异步，所有没有办法书写异步，所以最好return一个异步函数。
        useEffect(()=>{
            const  getHosSetList =  async()=>{
                setIsLoading(true)
                const result = await getHosSetListRequest({
                    page: current,
                    limit: pageSize,
                    ...fieldValue
                })
                setCurrent(result.current)
                setTableData (result.records)
                setTotal (result.total)
                setIsLoading(false)
            } 
            getHosSetList()
        },[current,pageSize,fieldValue,reRender])
      
    //点击删除事件
      const  deleteHosHandle = (id:number)=>{
        return  async ()=>{
            await deleteHosSetFromIdRequest(id)

            setReRender(!reRender)
            message.success("删除数据成功")
        }
      }
      //点击批量删除事件
      const batchDeleteHandle = async ()=>{
        //发送批量删除请求
        await  batchDeleteHosRequest(bacthSelectIds)

        message.success('批量删除成功')
            //重新渲染
        setReRender(!reRender)

          //恢复删除按钮为灰色
          setIsSelecte(true)
      }


      //colums是控制表格的字段有哪些,title属性就是当前的字段名称,dataIndex就是用来和将来的数据进行一一对应的
      const columns = [
        {
            title: '序号',
            width:60,
            render(_: any, __: any, index: number) {
              return( index + 1 )
            }
          },
          {
            title: '医院名称',
            dataIndex: 'hosname',
            
          },
          {
            title: '医院编号',
            dataIndex: 'hoscode',
          },
          {
            title: 'api基础路径',
            dataIndex: 'apiUrl',
          },
          {
            title: '签名',
            dataIndex: 'signKey',
          },
          {
            title: '联系人姓名',
            dataIndex: 'contactsName',
          },
          {
            title: '联系人手机',
            dataIndex: 'contactsPhone',
          },
          {
            title: '操作',
            fixed: "right" as "right",
            width:120,
            //render渲染时候有
            render(_:any,data:getHosSetListItemsType) {          
              const {id} =data
              console.log(data);
              
              return (
                <div>
                  <Tooltip title='修改医院'>
                    <Button
                      type='primary'
                      icon={<EditOutlined />}
                      className={style.mr}
                      onClick={() => { Navigate(`/syt/hospital/updatehosset/${id}`) }}
                    ></Button>
                  </Tooltip>

                  <Tooltip title='删除医院'>
                    <Button
                      type='primary'
                      danger
                      icon={<DeleteOutlined />}
                      onClick={deleteHosHandle(id)}
                    ></Button>
                  </Tooltip>

                </div>
              )
            }
          }
      ];

      //表单改变事件
      const  pageChangeHandle = (current:number,pageSize:number)=>{
        //点击后设置改变
        setCurrent(current)
        setPageSize(pageSize)
      }

      //onFinish的监听事件改变
      const searchHosFinishHandle = (FieldValue:searchHosFinishPraType)=>{
        setFieldValue(FieldValue)
      }

      //点击添加事件跳转新页面
      const addHosHandle = ()=>{
        Navigate("/syt/hospital/addhosset")
      }

      
  return (
<div className={style.outer}>
    <Card>
      <Form
        name="basic"
        wrapperCol={{ span: 30 }}
        layout='inline'
        onFinish={searchHosFinishHandle}
      >
        <Form.Item
          name="hosname"
        >
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item
          name="hoscode"
        >
          <Input placeholder='医院编号' />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 7, span: 16 }}>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
            查询
          </Button>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="default" htmlType="reset">
            清空
          </Button>
        </Form.Item>
      </Form>
      <div className={style.mt}>
        <Button type='primary' className={style.mr}  onClick={addHosHandle}>添加</Button>
        <Button type="primary" danger disabled={isSelecte} onClick={batchDeleteHandle}>批量删除</Button>
      </div>


      <Table
       className={style.mt} 
       columns={columns}
        dataSource={tableData} 
        scroll={{ x: 1400 }}
        bordered
        rowSelection={{
          onChange(ids:Key[]){
            setIsSelecte(!ids.length)
            setBatchSelectIds(ids)
          }
        }}
        pagination={{
            //当前页码
            current,
            //总数据的数量
            total,
            //每页条数
            pageSize,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [2, 3, 4, 5,50],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            showTotal(total) {
              return `总共有${total}条数据`
            },
            onChange : pageChangeHandle
        }}
        rowKey="id"
        loading={isLoading}
        />
    </Card>
    </div>
  )
}
